package com.zhentao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.UserHolder;
import com.zhentao.dto.UserDTO;
import com.zhentao.mapper.TbBlogMapper;
import com.zhentao.pojo.TbBlog;
import com.zhentao.service.TbBlogService;
import com.zhentao.util.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
* @author 宇
* @description 针对表【tb_blog】的数据库操作Service实现
* @createDate 2025-07-10 15:39:45
*/
@Service
public class TbBlogServiceImpl extends ServiceImpl<TbBlogMapper, TbBlog>
    implements TbBlogService{
    private static final String BLOG_LIKED_KEY = "blog:liked:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result likeBlog(Long id, String userId) {
        // 检查参数
        if (id == null) {
            return Result.fail("博客ID不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            return Result.fail("用户ID不能为空，请先登录");
        }

        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        if (score == null) {
            // 用户未点赞，执行点赞操作
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
        } else {
            // 用户已点赞，取消点赞
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId);
            }
        }
        return Result.ok();
    }

    @Override
    public Result isLiked(Long id, String userId) {
        // 检查参数
        if (id == null) {
            return Result.fail("博客ID不能为空");
        }
        if (userId == null || userId.trim().isEmpty()) {
            return Result.fail("用户ID不能为空，请先登录");
        }

        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        boolean isLiked = score != null;

        return Result.ok(isLiked);
    }
    private void isBlogLiked(TbBlog blog) {
        UserDTO user=UserHolder.getUser();
        if (user == null){
            return;
        }
        String userId=user.getId().toString();
        String key="blog:liked:" + blog.getUserName();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        blog.setIsLike(score != null);
    }


}




